function LoadConfirmOrderpage(){
	closeWaitingDialog();
	openConfirmOrderPage();
	displayTask();
	displayHistoryTable();
	fillOrderListDetail();
	createtitleOrder();
}

function addTaskToOrderList(){
	var posresid = getObjectFromDataIndex(SharedData.POSReservationTable,"tableId",getCurrentTable().table.id).id;
	var title = $("[name=POSNoteArea]").find("textarea").val();
	if($.trim(title)=="") return;
	componentLoading($("[name=POSNoteArea]"));
	$("[name=POSNoteArea]").find("input[type=button]").attr("disabled", "disabled");
	simpleserviceWithError("/POSgenerateOrderService",{func:"AddNote",posresid:posresid,title:$.trim(title)},function(data){
		closeComponentLoading($("[name=POSNoteArea]"));
		var tab = getCurrentTable();
		tab.POSHistory = JSON.parse(data);
		FillPOSHistory();
		delete tab.DisplayAddTask;
		displayTask();
	},function(data){
		closeComponentLoading($("[name=POSNoteArea]"));
	});
}

function clickAddTask(){
	var tab = getCurrentTable();
	if(tab.DisplayAddTask != null && tab.DisplayAddTask == true)
		delete tab.DisplayAddTask;
	else
		tab.DisplayAddTask = true;
	displayTask();
}

function displayTask(){
	var tab = getCurrentTable();
	var display = "";
	if(tab.DisplayAddTask == null || !tab.DisplayAddTask){ display="none"; $("[name=POSNoteArea]").find("textarea").val("");};
	$("[name=POSNoteArea]").css("display",display);
}

function clickHistoryTable(){
	var tab = getCurrentTable();
	if(tab.DisplayHistory != null && tab.DisplayHistory == true)
		delete tab.DisplayHistory;
	else
		tab.DisplayHistory = true;
	displayHistoryTable();
}

function displayHistoryTable(){
	var tab = getCurrentTable();
	var display = (tab.DisplayHistory == null || !tab.DisplayHistory)? "none":"";
	$("[name=POSAllHistory]").css("display",display);
	loadHistoryTable();
}

function loadHistoryTable(force){
	if($("[name=POSAllHistory]").is(":visible") || force){
		var posresid = getObjectFromDataIndex(SharedData.POSReservationTable,"tableId",getCurrentTable().table.id).id;
		componentLoading($("[name=POSAllHistory]"));
		simpleserviceWithError("/POSgenerateOrderService",{func:"GetAllPOSHistory",guestTableId:posresid},function(data){
			closeComponentLoading($("[name=POSAllHistory]"));
			var objArray = JSON.parse(data);
			objArray.sort(function(a, b) {return new Date(b.stampDate) - new Date(a.stampDate);});
			
			var tab = getCurrentTable();
			tab.POSHistory = {data:[objArray[0]],count:objArray.length};
			FillPOSHistory();
			$(".historyTable").find("tr").not(":first").remove();
			for(var i=0;i<objArray.length;i++)
				$(".historyTable").find("tr:last").after("<tr>" +
					"<td>"+objArray[i].change+"</td>" +
					"<td>"+new Date(objArray[i].stampDate).getFormatedDateTime()+"</td>" +
					"<td>"+objArray[i].user+"</td>" +
					"<td>"+objArray[i].title+"</td>" +
					"</tr>");
		},function(data){
			closeComponentLoading($("[name=POSAllHistory]"));
		});
	}else
		loadPOSHistory(force);
}

function loadPOSHistory(force){
	componentLoading($(".historybox"));
	var tab = getCurrentTable();
	if(tab.POSHistory == null || force){
		var guestTable = getObjectFromDataIndex(SharedData.POSReservationTable,"tableId",tab.table.id);
		simpleserviceWithError("/POSgenerateOrderService",{func:"GetPOSHistory",guestTableId:guestTable.id},function(data){
			closeComponentLoading($(".historybox"));
			getCurrentTable().POSHistory = JSON.parse(data);
			FillPOSHistory();
		},function(data){
			closeComponentLoading($(".historybox"));
		});
	}
	else
		FillPOSHistory();
}

function FillPOSHistory(){
	$(".historybox").find("div").remove();
	var objArray = getCurrentTable().POSHistory;
	$("[name=historyAmt]").html("&nbsp;("+objArray.count+")")
	for(var i=0;i<objArray.data.length;i++)
		$(".historybox").append("<div>"+new Date(objArray.data[i].stampDate).getFormatedDateTime()+", "+objArray.data[i].user+" "+objArray.data[i].change.toLowerCase()+" : <br/>"+objArray.data[i].title+"</div>");
}

function openConfirmOrderPage(){
	fillOrderListGenerateOrderPage();
}

function CloseTransaction(){
	closeTabTable();
	switchTab($("#tabs .tab:first"));
}

function fillOrderListGenerateOrderPage(autoSelect){
	var tab = getCurrentTable();
	var totalPrice = 0;
	$(".genOrder_orderList_body").children().remove();
	for(var i=0;i<tab.OrderList.length;i++)
	{
		var clss = (tab.activeOrderId == tab.OrderList[i].id)? "orderItem orderActive":"orderItem";
		var ordertitle = "Order";
		if(!tab.OrderList[i].status){
			clss+=" canceledOrder";
			ordertitle = "Canceled Order";
		}
		var item = '<div class="'+clss+'" refid="{0}" onclick="SelectDisplayOrderDetail($(this).attr(\'refid\'),true)"><div><div class="mid" style="margin: 10px 10px;">'
			+'<div class="genOrder_icon item_OrderListicon inlineb" style="float:left"></div><div class="inlineb"><div class="btnStrong tbcell">'+ordertitle+'</div><div class="tbcell" name="orderItemAmt">#{1} ({2} items)</div><div class="item_genOrder_folio">folio#{3}</div></div></div>'
			+'<div class="mid price btnStrong">{4}</div><div class="minprintIcon"><div class="genOrder_icon print_OrderListicon"></div></div>'
			+'</div></div>';
		var price = 0;
		var count = 0;
		for(var j=0;j<tab.OrderList[i].items.length;j++){
			if(tab.OrderList[i].items[j].item!=null){
				var posItem = getObjectFromSharedData(SharedData.Item,tab.OrderList[i].items[j].item);
				var displayPrice = (SharedData.General.incloudetax)? posItem.price + posItem.totalTax: posItem.price;
			}else{
				var totleTax = tab.OrderList[i].items[j].tax[0].taxValue;
				var displayPrice = (SharedData.General.incloudetax)? tab.OrderList[i].items[j].price + totalTax: tab.OrderList[i].items[j].price;
			}
			var priceAndTax = calPriceAndTaxWithQuantity(tab.OrderList[i].items[j]);
			var p = ((tab.OrderList[i].items[j].price * tab.OrderList[i].items[j].amount) - tab.OrderList[i].items[j].discount);
			price += priceAndTax.displayPriceTotal;
			count += tab.OrderList[i].items[j].amount;
		}
		tab.OrderList[i].folioIndex = i+1;
		tab.OrderList[i].totalPrice = price;
		tab.OrderList[i].totalAmount = count;
		$(".genOrder_orderList_body").append(item.format(
			tab.OrderList[i].id,
			i+1,
			count,
			tab.OrderList[i].displayId,
			toCurrencyString(price)
		));
		if(tab.OrderList[i].status) totalPrice += price;
	}
	$("[name=totalAry]").html(toCurrencyString(totalPrice));
	if(autoSelect==null||autoSelect==true){
		if(tab.activeOrderId!=null)
			SelectDisplayOrderDetail(tab.activeOrderId);
		else
			SelectDisplayOrderDetail(tab.OrderList[tab.OrderList.length-1].id)
	}
}

function confirmDialogForEditOrder(callbackOK,callbackNo,args){
	var content = "Order has edited, You want to save?";
	var buttons = [
		{ title:"OK", callback: function(thisdialog,args){
			thisdialog.dialog("close");
			callbackOK(args);
		}},
		{ title:"No", callback: function(thisdialog,args){
			thisdialog.dialog("close");
			callbackNo(args);
		}},
		{ title:"Cancel", callback: function(thisdialog,args){
			thisdialog.dialog("close");
		}}
	];
	return customDialog(simpleLabel_Message,content,null,buttons,args);
}

function SelectDisplayOrderDetail(orderId,checkEditOrder){
	var tab = getCurrentTable();
	
	if(checkEditOrder==true && tab.EditOrder!=null)
		confirmDialogForEditOrder(updateOrder,CancelEditOrder,orderId);
	else{
		$(".genOrder_orderList_body .orderItem[refid]").removeClass("orderActive");
		$(".genOrder_orderList_body .orderItem[refid="+orderId+"]").addClass("orderActive");
		var order = (tab.EditOrder!=null)? tab.EditOrder : getObjectFromSharedData(tab.OrderList,orderId);
		if(order.status){
			$('[name=genOrder_Orderdetail]').removeClass("CancelOrderDetail");
			$(".canceloverlay").css("display","none");
		}
		else{
			$('[name=genOrder_Orderdetail]').addClass("CancelOrderDetail");
			$(".canceloverlay").css("display","block");
		}
		var items = order.items;
		tab.activeOrderId = orderId;
		$("table[name=table_folio_item]").find("[name=item],[name=fillItem]").remove();
		$("table[name=table_folio_item]").attr("orderId",orderId);
		$(".Orderdetail_foliotital").find("span:not(:first)").remove();
		$(".Orderdetail_foliotital").find("span").after("<span> "+order.displayId+"</span>");
		var data = "<tr name='item' refid='{0}'><td>{1}</td><td class='productname'><div>{2}</div></td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td><td>{7}</td><td name='actionIconWhenUpdate'><div class='updateorderlistIcon delitemIcon' style='background-position: -154px -122px;' onclick='removeEditItem($(this))'></div></td></tr>";
		var discountSummary = 0;
		var taxSummary = 0;
		var priceSummary = 0;
		for(var i=0,index=1;i<items.length;i++){
			if(!items[i].status) continue;
			if(items[i].item!=null){
				var posItem = getObjectFromSharedData(SharedData.Item,items[i].item);
				var displayPrice = (SharedData.General.incloudetax)? posItem.price + posItem.totalTax: posItem.price;
			}else{
				var posItem = {displayId:""};
				var totalTax = 0;
				if(items[i].tax!=null) for(var j=0;j<items[i].tax.length;j++) totalTax += items[i].tax[j].taxValue;
				var displayPrice = (SharedData.General.incloudetax)? items[i].price + totalTax: items[i].price;
			}
			var priceAndTax = calPriceAndTaxWithQuantity(items[i]);
			var itemId = (items[i].id==null)? guid() : items[i].id;
			items[i].refId = itemId;
			var dataString = data.format(itemId,
				index,
				items[i].title,
				toCurrencyString(displayPrice),
				"<span class='link' onclick='editPOSOrderUnit($(this))'>" + items[i].amount + "</span>",
				"<span class='link' onclick='editPOSOrderDiscount($(this))'>" +toCurrencyString(items[i].discount) + "</span>",
				toCurrencyString(priceAndTax.taxPerItem * items[i].amount),
				toCurrencyString(priceAndTax.displayPriceTotal));
			var d = $("tr[name=item][refid]:last:visible");
			if(d.size()==0)
				$("tr[name=table_folio_header]:visible").after(dataString);
			else
				d.after(dataString);
			
			discountSummary += items[i].discount;
			taxSummary += (priceAndTax.taxPerItem * items[i].amount);
			priceSummary += priceAndTax.displayPriceTotal;
			index++;
		}
		$(function(){$(".canceloverlay").css("height",$(".canceloverlay").parent().height());});
		fillAddSuggestItem(afterSelectItem);
		fillDisplayOrderDetailSummary(discountSummary,taxSummary,priceSummary);
		$("table[name=table_folio_item]").find("[name=fillItem] .fillInputblock").focus();
	}
}

function fillAddSuggestItem(callback){
	var inputOrder=$("<tr name='fillItem'><td>&nbsp;</td><td class='productname' onclick='editTmpItem($(this))'><div class='searchItemOrder'><div class='genOrder_icon inputOrderItem'></div><input type='text' class='fillInputblock'></div></td><td name='price'>&nbsp;</td><td><input type='text' style='width:30px;' name='unit'></td><td name='discount'>"+toCurrencyString(0)+"</td><td name='tax'>"+toCurrencyString(0)+"</td><td name='total'>"+toCurrencyString(0)+"</td><td name='del'>&nbsp;</td></tr>");
	$("[name=table_folio_item]:visible tr[refid]:last").after(inputOrder);
	handleUpdateItemSuggestionElement(inputOrder.find(".fillInputblock"),callback);
}

function fillDisplayOrderDetailSummary(discountSummary,taxSummary,priceSummary){
	$("[name=folio_totle_dis]").html(toCurrencyString(discountSummary));
	$("[name=folio_totle_tax]").html(toCurrencyString(taxSummary));
	$("[name=folio_totle_price]").html(toCurrencyString(priceSummary));
	/*var tab = getCurrentTable();
	var order = (tab.EditOrder!=null)? tab.EditOrder : getObjectFromSharedData(tab.OrderList,tab.activeOrderId);
	var totaldiscount = 0;
	for(var i=0;i<order.items.length;i++){
		totaldiscount += order.items[i].discount;
	}*/
	$(".chSummaryTotal[name=subTotal] .chRight").html(toCurrencyString(0));
	$(".chSummaryTotal[name=discount] .chRight").html(toCurrencyString(discountSummary));
	$(".chSummaryTotal[name=total] .chRight").html(toCurrencyString(priceSummary));
	$(".chSummaryTotal[name=tax] .chRight").html(toCurrencyString(taxSummary));
	$(".chSummaryTotal[name=paid] .chRight").html(toCurrencyString(0));
	$(".chSummaryTotal[name=balance] .chRight,[name=balanceAmt]").html(toCurrencyString(0));
}

function editPOSOrderUnit(dom){
	fillSimpleTextEditWithNumpad(dom,true,function(obj){
		var id = obj.dom.parents("tr:first").attr("refid");
		var tab = getCurrentTable();
		var q = obj.textbox.val();
		if(q == obj.dom.text()) return;
		cloneEditObject();
		var obj = getObjectFromDataIndex(tab.EditOrder.items,"refId",id);
		if(obj.refItem!=null)
			var tax = getPOSTaxPercFixFromItem(obj.refItem);
		else{
			var tax = getSharedDataPOSTax();
		}
		obj.amount = parseInt(q);
		delete obj.tax;
		var tmp = customCalTax(obj.price,tax.perc,tax.fix,obj.discount,obj.amount);
		obj.tax = [{taxValue:tmp.totalTax/obj.amount}];
		SelectDisplayOrderDetail(tab.activeOrderId);
	},dom,true);
}

function editPOSOrderDiscount(dom){
	fillSimpleTextEdit(dom,true,function(obj){
		if(currencyStringToNumber(obj.dom.text()) == obj.textbox.val()) return;
		var id = obj.dom.parents("tr:first").attr("refid");
		var tab = getCurrentTable();
		var discount = obj.textbox.val();
		cloneEditObject();
		var obj = getObjectFromDataIndex(tab.EditOrder.items,"refId",id);
		if(obj.refItem!=null)
			var tax = getPOSTaxPercFixFromItem(obj.refItem);
		else{
			var tax = getSharedDataPOSTax();
		}
		obj.discount = parseFloat(discount);
		delete obj.tax;
		var tmp = customCalTax(obj.price,tax.perc,tax.fix,obj.discount,obj.amount);
		obj.tax = [{taxValue:tmp.totalTax/obj.amount}];
		SelectDisplayOrderDetail(tab.activeOrderId);
	},dom,true);
}
function removeEditItem(dom){
	var tr = dom.parents("tr:first");
	var tab = getCurrentTable();
	var order = getObjectFromSharedData(tab.OrderList,tab.activeOrderId);
	var item = getObjectFromSharedData(order.items,tr.attr("refid"));
	var dialogtitle = item.title + " / "+item.amount + " unit(s) / "+tr.find(".productname").next().html();
	confirmDialog("Confirm to delete<br/>" +dialogtitle,function(args){
		cloneEditObject();
		var obj = getObjectFromDataIndex(args.tab.EditOrder.items,"refId",args.tr.attr("refId"));
		if(obj.id==null)
			args.tab.EditOrder.items.splice(args.tab.EditOrder.items.indexOf(obj),1);
		else
			obj.status = false;
		SelectDisplayOrderDetail(args.tab.activeOrderId);
	},{tr:tr,tab:tab});
}
function fillOrderListDetail(){
	var Tabs =getCurrentTable();
	var name = "-";
	var date = "-";
	var tel = "-";
	var hours = "-";
	var minutes = "-";
	if(Tabs.OwnerTable!=null){
		var data =getObjectFromSharedData(SharedData.POSReservationTable,Tabs.OwnerTable.resId)
		if(Tabs.OwnerTable.Name!=null)name=Tabs.OwnerTable.Name;
		if(data.Arrivel!=null)date=data.Arrivel;
		if(data.tel!=null)tel=data.tel;
		if(date!=null){
			var hours = new Date(date).getHours();
			var minutes =new Date(date).getMinutes();
		}
	}
	$('[name=genOrder_guestName]:visible').text(name);
	$('[name=genOrder_guestTel]:visible').text(tel);
	$('[name=genOrder_date]:visible').text(new Date(date).getFormatedString());
	$('[name=genOrder_time]:visible').text(hours+":"+minutes);
}

function openPaymentPage(){
	var Tabs = getCurrentTable();
	Tabs.pagetitle = "payment";
	switchTab();
}

function createtitleOrder(){
	var Tabs =getCurrentTable();
	if(Tabs == null)return;
	$('[name=tabletitle_forOrder').children().remove();
	//if($('[name=tabletitle_forOrder]').children().size() == 0)
		$('[name=tabletitle_forOrder]:visible').append('<div style="display:inline-block;">'+titleTable+" "+Tabs.table.tableTitle +'</div><span style="color:#000">  <  </span><div name="OrderNumber" style="display:inline-block;color:#000">'+titleConfirmOrder+'</div>');
}

function handleUpdateItemSuggestionElement(dom,callback){
	dom.keydown(function(e){
		$(this).parents("tr:first").find("[name=price]").html("");
		$(this).parents("tr:first").removeAttr("refid")
		var l = ($(this).val() + String.fromCharCode(e.keyCode)).length;
		if(e.keyCode == 46 || e.keyCode == 8){
			l = l-1;
		}
		if(l >= 2){
			var data = getListOfFieldId(SharedData.Item,"title");
			if(!dom.hasClass("ui-autocomplete-input"))
			dom.autocomplete({
				source: data,
				open: function(){
					$(".ui-autocomplete:visible li>a").each(function(){
						var item = getObjectFromDataIndex(SharedData.Item,"title",this.innerText);
						var price = item.price;
						if(SharedData.General.incloudetax)
							price += item.totalTax;
						this.innerHTML = "<span>"+this.innerText+"</span><span style='float:right'>"+toCurrencyString(price)+"</span>";
					});
				},
				select: callback
			});
		}
		else{
			if(dom.hasClass("ui-autocomplete-input")){
				dom.autocomplete("destroy");
			}
		}
	});
}
function afterSelectItem(e,s){
	var item = getObjectFromDataIndex(SharedData.Item,"title",s.item.label);
	var price = item.price;
	if(SharedData.General.incloudetax)
		price += item.totalTax;
	$(this).parents("tr:first").find("[name=price]").html(toCurrencyString(price));
	$(this).parents("tr:first").attr("refid",item.id);
	
	$(this).parents("td:first").find(".searchItemOrder").css("display","none");
	$(this).parents("td:first").append("<div style='width: calc(100% - 40px)';>"+item.title+"</div>");
	
	var unit = $(this).parents("tr:first").find("[name=unit]");
	unit.focus();
	numpad(unit,null,unitEdit,this);
}

function handleUpdateItemUnit(){
	$("[name=fillItem] [name=unit]").click(function(){numpad(this,null,unitEdit)});
}

function editTmpItem(dom){
	if(dom.find(".searchItemOrder").is(":visible")) return;
	dom.find(":visible").remove();
	dom.find(".searchItemOrder").css("display","");
}

function unitEdit(el){
	if($("[name=fillItem] .searchItemOrder:visible").size()>0) {$("[name=fillItem] .fillInputblock").focus(); return;}
	var tab = getCurrentTable();
	if($(el).parents("tr:first").find(".delitemIcon").size()==0){
		var tr = $(el).parents("tr:first");
		var item = getObjectFromSharedData(SharedData.Item,tr.attr("refid"));
		
		cloneEditObject();
		var tab = getCurrentTable();
		var tmp = getObjectFromDataIndex(tab.EditOrder.items,"item",item.id);
		var tmpAmount = tr.find('[name=unit]').val();
		var amount = (tmpAmount=="")?0:parseInt(tr.find('[name=unit]').val());
		if(tmp!=null){
			if(tmp.status)
				tmp.amount += amount;
			else{
				tmp.amount = amount;
				tmp.discount = 0;
				tmp.tax = [{taxValue:tmp.refItem.totalTax}];
				tmp.status = true;
				tab.EditOrder.items.push(tab.EditOrder.items.splice(tab.EditOrder.items.indexOf(tmp),1)[0]);
			}
		}
		else
			tab.EditOrder.items.push({amount:amount,
				discount:currencyStringToNumber(tr.find('[name=discount]').text()),
				item:tr.attr("refid"),
				refItem: item,
				price:item.price,
				tax:[{taxValue:item.totalTax}],
				title:item.title,
				type:'fillItem',
				status:true});
	}
	SelectDisplayOrderDetail(tab.activeOrderId);
}

function getPOSTaxPercFixFromItem(item){
	var rs = {perc:0,fix:0};
	if(item.tax!=null){
		var ids = item.tax.split(",");
		for(var i=0;i<ids.length;i++)
		{
			var t = getObjectFromSharedData(SharedData.POSTax,ids[i]);
			if(t.isPercent)
				rs.perc += t.currencyValue;
			else
				rs.fix += t.currencyValue;
		}
	}
	return rs;
}

function cloneEditObject(){
	var tab = getCurrentTable();
	if(tab.EditOrder == null)tab.EditOrder = jQuery.extend(true,{},getObjectFromSharedData(tab.OrderList,tab.activeOrderId));
}

function updateOrder(){
	var tab = getCurrentTable();
	if(tab.EditOrder == null) return;
	var orderId = tab.EditOrder.id;
	var items = [];
	for(var i=0;i<tab.EditOrder.items.length;i++){
		var _item = tab.EditOrder.items[i];
		var tmp = {a:_item.amount,discount:_item.discount};
		if(_item.id!=null){
			tmp.id = _item.id;
			tmp.s = _item.status;
		}else if(_item.item!=null){
			tmp.item = _item.item;
		}else{
			tmp.title = _item.title;
			tmp.price = _item.price;
			tmp.tax = SharedData.POS.listPOSTaxString;
		}
		if(_item.refItem==null)
			tmp.tax = SharedData.POS.listPOSTaxString;
		items.push(tmp);
	}
	var itemsString = JSON.stringify(items);
	waitingDialog();
	simpleserviceWithError("/POSgenerateOrderService",{func:"EditOrder",orderId:orderId,items:itemsString},function(data,args){
		var objArray = new Array();
		objArray = JSON.parse(data);
		var checkLogOut = checkSessionPOS(objArray);
		if(checkLogOut)
			return;
		closeWaitingDialog();
		var tab = getCurrentTable();
		var order = getObjectFromSharedData(tab.OrderList,tab.activeOrderId);
		order.items = JSON.parse(data).items;
		delete tab.EditOrder;
		SelectDisplayOrderDetail(tab.activeOrderId);
		fillOrderListGenerateOrderPage(false);
		caltotalPriceForFillTable(tab);
	},function(data,args){
		closeWaitingDialog();
		simpleDialog("Update Order Fail");
	});
}

function caltotalPriceForFillTable(tab){
	var total = 0;
	for(var i=0;i<tab.OrderList.length;i++){
		if(!tab.OrderList[i].status) continue;
		for(var j=0;j<tab.OrderList[i].items.length;j++){
			var item = tab.OrderList[i].items[j];
			if(!item.status) continue;
			var priceAndTax = calPriceAndTaxWithQuantity(item);
			total += priceAndTax.displayPriceTotal;
		}
	}
	var res = getObjectFromSharedData(SharedData.POSReservationTable,tab.posresid);
	res.money = total;
	fillPOSResTable();
}

function CancelEditOrder(orderId){
	var tab = getCurrentTable();
	delete tab.EditOrder;
	if(orderId==null) orderId=tab.activeOrderId;
	SelectDisplayOrderDetail(orderId);
}
function POScustomCharge(){
	loadDynamicJSP($("div[for=pageload]"),"/POS/dialog/POS_CustomCharge.jsp",waitingDialog,function(resp,obj){
		$("[id='BlankDialog'][scrolltop]").dialog("close");
		closeWaitingDialog();
			var buttons = [
				{ title:btnSave , callback: function(thisdialog,args){
					AddcustomCharge();
					thisdialog.dialog("close");
				}},
				{ title:btnCancel , callback: function(thisdialog,args){
					thisdialog.dialog("close");
				}}
			];
			customDialog(taitleCustom,$("[id=payment_charges_popup]").html(),{ width: 700},buttons,null);
			$('[name=payment_charges_popup]').css('width','680px');
			$('[name=payment_charges_popup]:visible').parent().css('width','680px');
	});
}

function calCustomCharge(){
	var ChargeInputPrice =$('[name=POS_customCharge_inputprice]:visible').val();
	var Amt =$('[name=POS_customCharge_qty]:visible').val();
	var discount=0;
	var p=0; var i=0;
	if(ChargeInputPrice)
	for(var _i=0;_i<SharedData.POS.taxList.length;_i++)
		(SharedData.POS.taxList[_i].isPercent)? p+=SharedData.POS.taxList[_i].currencyValue:i+=SharedData.POS.taxList[_i].currencyValue;
	
	discount = $('[name=POS_customCharge_discount]:visible').val();
	var discStatus=$('[name=group1]:visible:checked').val();
	var priceNoTax=calPriceWithoutTax(ChargeInputPrice,p,i);
	if(discStatus!="cash"){
		discount= priceNoTax*(discount/100) * Amt;
	}
	var balance =customCalTax(priceNoTax,p,i,discount,Amt,SharedData.General.incloudetax);
	$('[name=POS_customCharge_balance]:visible').html(toCurrencyString(balance.totalPrice,false));
}

function isNumberKey(evt)
{
	var charCode = (evt.which) ? evt.which : event.keyCode
	if(charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	return true;
}

function AddcustomCharge(){
	var ChargeInputPrice =$('[name=POS_customCharge_inputprice]:visible').val();
	var Amt =$('[name=POS_customCharge_qty]:visible').val();
	var discount=0;
	discount = $('[name=POS_customCharge_discount]:visible').val();
	var discStatus=$('[name=group1]:visible:checked').val();
	var p=0; var i=0;
	if(ChargeInputPrice)
	for(var _i=0;_i<SharedData.POS.taxList.length;_i++)
		(SharedData.POS.taxList[_i].isPercent)? p+=SharedData.POS.taxList[_i].currencyValue:i+=SharedData.POS.taxList[_i].currencyValue;
	
	var priceNoTax=calPriceWithoutTax(ChargeInputPrice,p,i,SharedData.General.incloudetax);
	if(discStatus!="cash"){
		discount= priceNoTax*(discount/100);
	}
	var balance =customCalTax(priceNoTax,p,i,discount,Amt,SharedData.General.incloudetax);
	var tab = getCurrentTable();
	if(tab.PaymentList == null){
		cloneEditObject();
		tab.EditOrder.items.push({
			amount:parseInt(Amt),
			discount: parseFloat(discount),
			price:parseFloat(ChargeInputPrice),
			status: true,
			title: $('[name=POS_customCharge_title]:visible').val(),
			tax:[{taxValue:balance.totalTax/parseInt(Amt)}]
		});
		SelectDisplayOrderDetail(tab.activeOrderId);
	}else{
		cloneOrderPaymentObject();
		tab.PaymentOrder.push({
			amount:parseInt(Amt),
			discount: parseFloat(discount),
			price:parseFloat(ChargeInputPrice),
			status: true,
			refId:guid(),
			title: $('[name=POS_customCharge_title]:visible').val(),
			tax:[{taxValue:balance.totalTax}]
		});
		selectDisplayPaymentItemDetail();
	}
}

function AddcustomChargeSuccess(data,obj){
	var objArray= JSON.parse(data);
	if(objArray == null){
		simpleDialog(saveFail_label,100,null);
	}else{
		fillOrderListGenerateOrderPage(false);
	}
}

function cancelOrderFunc(id){
	var tab = getCurrentTable();
	if(id==null) id=tab.activeOrderId;
	loadDynamicJSP($("div[for=pageload]"),"/POS/dialog/CancelOrder.jsp",waitingDialog,function(resp,obj){
		closeWaitingDialog();
		var dialog = customDialog(CancelOrderTitle,$("div[for=pageload] [file='/POS/dialog/CancelOrder'] div").html());
		dialog.parents(".ui-dialog:first").css("min-width","340px");
		dialog.parents(".ui-dialog:first").css("width","auto");
		var order = getObjectFromSharedData(obj.tab.OrderList,obj.id);
		var items = (order.totalAmount>1)? "items":"item";
		dialog.find(".item_genOrder_folio").html("folio#"+order.displayId);
		dialog.find("[name=orderItemAmt]").html("#"+order.folioIndex+" ("+order.totalAmount+" "+items+")");
		dialog.find(".price").html(toCurrencyString(order.totalPrice));
		var buttons = [
			{ title:"OK", callback: function(thisdialog,args){
				thisdialog.dialog("close");
				CancelOrderDialogEvent(thisdialog,args);
			}},
			{ title:"Cancel", callback: function(thisdialog,args){
				thisdialog.dialog("close");
			}}
		];
		bindButtonDialog(dialog,buttons,obj);
	},{id:id,tab:tab});
}

function CancelOrderDialogEvent(dialog,args){
	simpleserviceWithArgs("/POSgenerateOrderService",{func:"CancelOrder",orderId:args.id},function(data,args){
		var objArray = JSON.parse(data);
		var order = getObjectFromSharedData(args.tab.OrderList,objArray.id);
		order.status = objArray.status;
		fillOrderListGenerateOrderPage(false);
		SelectDisplayOrderDetail(args.tab.activeOrderId);
		caltotalPriceForFillTable(args.tab);
	},args);
}